package com.youdianstar.app.common.widget.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.youdianstar.app.common.ConfigKey
import com.youdianstar.app.common.R
import com.youdianstar.app.common.util.DataManager
import com.youdianstar.app.common.widget.RadiusImageView


/**
 * File: MultiPicAdapter
 * Author: 82149 Create: 2021/10/28 14:46
 * Changes (from 2021/10/28)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class MultiPicAdapter(val context: Context,val maxNum :Int, val datas: MutableList<String>, val callback : OnPicSelect) :
    RecyclerView.Adapter<MultiPicAdapter.PicHolder>() {

    interface OnPicSelect {
        fun onAdd()

        fun onDelete(index:Int)
    }

    private var max = 3

    private var host = ""

    init {
        this.max = maxNum
        this.host = DataManager.instance.getConfig(ConfigKey.FILE_HOST)
    }

    class PicHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ivIcon by lazy {
            itemView.findViewById<RadiusImageView>(R.id.iv_select)
        }
        val ivDelete by lazy {
            itemView.findViewById<ImageView>(R.id.iv_delete)
        }
    }

    fun getDataList():List<String>{
        return datas
    }

    /**刷新数据*/
    fun refreshData(list: List<String>) {
        datas.clear()
        datas.addAll(list)

        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PicHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_item_image, parent, false)
        return PicHolder(view)
    }

    override fun onBindViewHolder(holder: PicHolder, position: Int) {
        if (datas.isEmpty() || position>=datas.size){
            holder.ivDelete.visibility = View.GONE
            holder.ivIcon.load(R.drawable.ic_img_picker_default){

            }
            //holder.ivIcon.setImageResource(R.drawable.ic_img_picker_add)
            holder.ivIcon.setOnClickListener {
                callback.onAdd()
            }
        } else {
            val pathStr = if(datas[position].contains("http")) datas[position] else host+datas[position]
            holder.ivIcon.load(pathStr){
                error(R.drawable.ic_img_picker_default)
            }
            holder.ivDelete.visibility = View.VISIBLE
            holder.ivDelete.setOnClickListener {
                callback.onDelete(position)
            }
        }
    }

    override fun getItemCount(): Int {
        val count: Int = if (datas.size == 0) 1 else datas.size + 1
        return if (count > max)
            datas.size
        else
            count
    }
}